package com.yitiao.socket.chatroom.bio;

import com.yitiao.socket.chatroom.CommonConst;
import lombok.SneakyThrows;

import java.io.*;
import java.net.Socket;

public class ChatHandler implements Runnable {
    private final ChatServer chatServer;
    private final Socket socket;

    public ChatHandler(ChatServer chatServer, Socket socket) {
        this.chatServer = chatServer;
        this.socket = socket;
    }

    @SneakyThrows
    @Override
    public void run() {
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        chatServer.addClient(socket);

        while (true) {
            String line = reader.readLine();
            if (line != null) {
                String msg = "client [" + socket.getPort() + "]:" + line;
                System.out.println(msg);
                chatServer.forwardMessage(socket.getPort(), msg);

                if (line.equals(CommonConst.QUIT)) {
                    chatServer.removeClient(socket.getPort());
                    break;
                }
            }
        }
    }
}
